package service_manager

import (
	pb "ReferenceMonitor/sdk/rpc/pb_gen"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"net"
)

func newServerRPC(addr string, dms *DeviceManager) *grpc.Server {
	lis, err := net.Listen("tcp", addr)
	if err != nil {
		fmt.Println("Start Gallery Service Failed: ", err)
		return nil
	}

	fmt.Println("Start Gallery Service At: ", addr)
	grpcServer := grpc.NewServer()
	pb.RegisterDeviceAuthenticationServer(grpcServer, &DeviceManagerRPC{dms: dms})
	go grpcServer.Serve(lis)

	return grpcServer
}

type DeviceManagerRPC struct {
	pb.UnimplementedDeviceAuthenticationServer
	dms *DeviceManager
}

func (s *DeviceManagerRPC) FindDevice(ctx context.Context, req *pb.Request) (*pb.DeviceInfo, error) {
	//dms
	s.dms.InitDeviceVerification(req.Msg)
	return &pb.DeviceInfo{
		Name: s.dms.CurDv.Name,
		Type: s.dms.CurDv.DType,
		Tag:  s.dms.CurDv.Tag,
	}, nil
}

func (s *DeviceManagerRPC) RegisterDevice(ctx context.Context, msg *pb.DeviceVerifyMsg) (*pb.Response, error) {
	//s.dms.
	if s.dms.RegisterDevices(msg.Info.Name, msg.Info.Type, msg.Info.Tag, msg.Msg) {
		return &pb.Response{Ok: true, Msg: "Device Register Success!"}, nil
	}
	return &pb.Response{Ok: false, Msg: "Failed to Register Device!"}, nil
}
